<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Models\Article;
use App\Models\ArticleCount;

class ArticleController extends BaseController
{
    //查询资讯列表
    public function articleList(){
        //后端默认传递page,自动进行分页了
          $data = Article::orderBy('id','desc')->select(['id','title','desn','pic','created_at'])->paginate($this->pagesize);
          return $data;
    }
    
    //查询资讯详情
    public function articleDetail(Article $article){
        return $article;
    }
    
    //统计文章的阅读人数
    public function articleCount(Request $request){
        //因为openid设置了唯一索引，所以这里是不会重复的
        $openid = $request->post('openid');
        $art_id = $request->post('art_id');
        $find = ArticleCount::where(['openid'=>$openid,'art_id'=>$art_id])->first();
        $data = [
            'openid' => $openid,
            'art_id' => $art_id,
            'vdt' => date('Y-m-d',time()),
            'vtime' => time()
        ];
        //这里使用try catch  的原因是   使用唯一索引的时候，出现再次添加相同数据会报错
        if(!$find){
            $model = ArticleCount::create($data);
        }else{
            return ['status' => 1001,'msg' => '数据已经存在'];
        }
        return $model;
        
    }
}
